<template>
  <div class="cube3d-container" :class="{ 'connected': isConnected, 'active': isActive }">
    <div class="cube3d" :class="`cube3d-${uniqueId}`" ref="cube3dRef"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import cube3d from '@/utils/cube3d.js'

// 定义props
const props = defineProps({
  cubeFace: {
    type: String,
    default: 'UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB'
  },
  isConnected: {
    type: Boolean,
    default: false
  },
  isActive: {
    type: Boolean,
    default: false
  },
  size: {
    type: String,
    default: 'normal', // small, normal, large
    validator: (value) => ['small', 'normal', 'large'].includes(value)
  }
})

const cube3dRef = ref(null)
let cubeGame = null
const uniqueId = ref(`cube-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`)

// 初始化cube3d
const initCube3D = async () => {
  if (!cube3dRef.value) return
  
  try {
    // 等待DOM更新
    await nextTick()
    
    // 延迟初始化，避免多个实例冲突
    setTimeout(() => {
      try {
        // 创建cube3d实例，使用唯一的类名
        cubeGame = new cube3d({
          el: `.cube3d-${uniqueId.value}`
        })
        
        // 设置初始魔方面状态
        if (props.cubeFace) {
          cubeGame.facelets.setFaceLets(props.cubeFace)
        }
        
        // 根据size属性设置渲染器尺寸
        if (cubeGame.world && cubeGame.world.renderer) {
          const size = getSizeDimensions(props.size)
          cubeGame.world.renderer.setSize(size.width, size.height)
          cubeGame.world.width = size.width
          cubeGame.world.height = size.height
          cubeGame.world.resize()
        }
        
        console.log('Cube3D初始化成功:', uniqueId.value, '尺寸:', props.size)
      } catch (error) {
        console.error('Cube3D初始化失败:', error)
      }
    }, 100 * Math.random()) // 随机延迟，避免同时初始化
    
  } catch (error) {
    console.error('Cube3D初始化失败:', error)
  }
}

// 获取尺寸对应的像素值
const getSizeDimensions = (size) => {
  switch (size) {
    case 'small':
      return { width: 80, height: 80 }
    case 'normal':
      return { width: 120, height: 120 }
    case 'large':
      return { width: 160, height: 160 }
    default:
      return { width: 120, height: 120 }
  }
}

// 更新魔方面状态
const updateCubeFace = (faceString) => {
  if (cubeGame && cubeGame.facelets) {
    cubeGame.facelets.setFaceLets(faceString)
  }
}

// 监听cubeFace变化
watch(() => props.cubeFace, (newFace) => {
  if (newFace && cubeGame) {
    updateCubeFace(newFace)
  }
}, { immediate: true })

// 监听size变化
watch(() => props.size, (newSize) => {
  if (cube3dRef.value) {
    // 移除旧的size类
    cube3dRef.value.classList.remove('size-small', 'size-normal', 'size-large')
    // 添加新的size类
    cube3dRef.value.classList.add(`size-${newSize}`)
    
    // 强制重新计算尺寸
    nextTick(() => {
      if (cubeGame && cubeGame.world && cubeGame.world.renderer) {
        const size = getSizeDimensions(newSize)
        cubeGame.world.renderer.setSize(size.width, size.height)
        cubeGame.world.width = size.width
        cubeGame.world.height = size.height
        cubeGame.world.resize()
        console.log('Cube3D尺寸已更新:', newSize, '新尺寸:', size)
      }
    })
  }
}, { immediate: true })

// 组件挂载
onMounted(() => {
  // 延迟初始化，确保DOM完全渲染
  setTimeout(() => {
    initCube3D()
  }, 200)
})

// 组件卸载
onUnmounted(() => {
  if (cubeGame) {
    try {
      // 清理cube3d资源
      if (cubeGame.world && cubeGame.world.renderer) {
        cubeGame.world.renderer.dispose()
      }
      cubeGame = null
    } catch (error) {
      console.error('清理Cube3D资源失败:', error)
    }
  }
})

// 暴露方法给父组件
defineExpose({
  updateCubeFace,
  cubeGame
})
</script>

<style lang="scss" scoped>
.cube3d-container {
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s ease;
  
  &.connected {
    transform: scale(1.1);
  }
  
  &.active {
    animation: pulse 2s infinite;
  }
  
  .cube3d {
    position: relative;
    
    // 默认大小 - 调整到合适尺寸
    &.size-small {
      width: 80px !important;
      height: 80px !important;
      canvas {
        width: 80px !important;
        height: 80px !important;
      }
    }
    
    &.size-normal {
      width: 120px !important;
      height: 120px !important;
      canvas {
        width: 120px !important;
        height: 120px !important;
      }
    }
    
    &.size-large {
      width: 160px !important;
      height: 160px !important;
      canvas {
        width: 160px !important;
        height: 160px !important;
      }
    }
  }
  
  // 为每个唯一的魔方类添加样式 - 调整到合适尺寸
  .cube3d[class*="cube3d-cube-"] {
    position: relative;
    
    &.size-small {
      width: 80px !important;
      height: 80px !important;
      canvas {
        width: 80px !important;
        height: 80px !important;
      }
    }
    
    &.size-normal {
      width: 120px !important;
      height: 120px !important;
      canvas {
        width: 120px !important;
        height: 120px !important;
      }
    }
    
    &.size-large {
      width: 160px !important;
      height: 160px !important;
      canvas {
        width: 160px !important;
        height: 160px !important;
      }
    }
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}
</style> 